
package de.uni.wuppertal.server.ftp;

import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Martin Schröder
 * @author Patrik Nordsiek
 */
public class FTPServerCommand
{
	private Pattern REGEX_COMMAND = Pattern.compile("([A-Z]+)\\s*(.*)", Pattern.CASE_INSENSITIVE);
	
	private String command = null;
	private Vector<String> arguments = new Vector<String>();
	
	public void parseLine(String line) throws Exception
	{
		reset();
		
		Matcher matcher = REGEX_COMMAND.matcher(line);
		
		if(!matcher.matches())
		{
			throw new FTPServerException(500);
		}
		
		command = matcher.group(1).toUpperCase();
		
		String args = matcher.group(2).trim();
		
		if(args.length() > 0)
		{
			for(String arg : args.split("\\s+"))
			{
				arguments.add(arg);
			}
		}
	}
	
	@Override
	public String toString()
	{
		StringBuffer buffer = new StringBuffer();
		
		buffer.append(command);
		
		for(String arg : arguments)
		{
			buffer.append(" ");
			buffer.append(arg);
		}
		
		return buffer.toString();
	}
	
	public void reset()
	{
		command = null;
		arguments.clear();
	}
	
	public boolean is(String command)
	{
		return this.command.equals(command.toUpperCase());
	}
	
	public String getCommand()
	{
		return command;
	}
	
	public int getArgumentCount()
	{
		return arguments.size();
	}
	
	public boolean hasArguments()
	{
		return arguments.size() > 0;
	}
	
	public String getArgument(int position)
	{
		try
		{
			return arguments.get(position);
		}
		catch(Throwable e)
		{
			return null;
		}
	}
	
	public String[] getArguments()
	{
		return arguments.toArray(new String[] {});
	}
}
